﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;
using NHibernate;

namespace MovieDB.Data.Repositories
{
    public class UnitOfWork : IUnitOfWork, IDisposable
    {
        private readonly ISession _session = null;
        private readonly TransactionScope _transactionScope = null;
        private bool _isRolledback = false;

        public UnitOfWork(ISession session)
        {
            _session = session;
            TransactionOptions options = new TransactionOptions();
            options.IsolationLevel = IsolationLevel.ReadCommitted;
            _transactionScope = new TransactionScope(TransactionScopeOption.Required, options);
        }

        public ISession Session
        {
            get { return _session; }
        }

        public void Rollback()
        {
            if (!_isRolledback)
            {
                _isRolledback = true;
                _transactionScope.Dispose();
            }
        }

        public void Dispose()
        {
            if (!_isRolledback)
            {
                try
                {
                    _transactionScope.Complete();
                }
                finally
                {
                    _transactionScope.Dispose();
                }
            }
        }
    }
}
